﻿namespace Mp3Observer.Common.Behaviors
{
    #region usings

    using System;
    using System.Windows;
    using System.Windows.Controls; 

    #endregion

    /// <summary>
    /// Makes the Source property of the WebBrowser Control from a normal Property into a dependency property (bindable!!)
    /// </summary>
    /// <example>
    /// <code>
    /// <![CDATA[ 
    /// <WebBrowser behaviors:WebBrowserUtility.BindableSource="{Binding BrowserSource}" />
    /// ]]>
    /// </code>
    /// </example>
    public static class WebBrowserUtility
    {
        /// <summary>
        /// BindableSource as DependencyProperty enables binding
        /// </summary>
        public static readonly DependencyProperty BindableSourceProperty =
            DependencyProperty.RegisterAttached("BindableSource", typeof(string), typeof(WebBrowserUtility), 
            new UIPropertyMetadata(null, BindableSourcePropertyChanged));

        /// <summary>
        /// Gets the bindable source.
        /// </summary>
        /// <param name="obj">The obj.</param>
        /// <returns></returns>
        public static string GetBindableSource(DependencyObject obj)
        { 
            return (string)obj.GetValue(BindableSourceProperty); 
        }

        /// <summary>
        /// Sets the bindable source.
        /// </summary>
        /// <param name="obj">The obj.</param>
        /// <param name="value">The value.</param>
        public static void SetBindableSource(DependencyObject obj, string value)
        {
            obj.SetValue(BindableSourceProperty, value); 
        }

        /// <summary>
        /// Called the BindableSource property changed; browser.source is set to the new uri.
        /// </summary>
        /// <param name="o">The o.</param>
        /// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
        public static void BindableSourcePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            WebBrowser browser = o as WebBrowser; 
            if (browser != null)
            {
                string uri = e.NewValue as string;
                if (uri.IsNullOrEmpty())
                    return;
                browser.Source = uri != null ? new Uri(uri) : null; }
        } 
    }
}
